<template>
    <TableCard ref="table" :data="data"></TableCard>
    <Detail :data="details" @closed = "closeAddOrEdit" v-if = "details.open"></Detail>
</template>

<script setup lang="ts">
import TableCard from '@/components/layout/TableCard.vue'
import { type TableCardType, SearchBoxColumnType, type TableSelectOne } from '@/assets/js/utils/entity/TableCardType'
import type { VMenuManagement } from '@/assets/js/vo/settings/menuManagement/VMenuManagement'
import { reactive, ref } from 'vue'
import { listMenu, removeMenu } from '@/api/settings/menuManagement'
import Detail from './components/Detail.vue'
import { ElMessage } from 'element-plus'
import type { HttpResponse } from '@/assets/js/utils/entity/HttpResponse'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'


const closeAddOrEdit = () => {
    table.value.query()
}
const details = reactive<TableSelectOne>({
    open: false,
    title: '新增菜单',
    id: null,
    callback: closeAddOrEdit
})

const table = ref()

const add = () => {
    details.open = true
    details.id = null
}

const edit = (datas: VMenuManagement[]) => {
    if (!datas.length) {
        ElMessage.warning('请至少选择一条数据进行修改操作！')
        return
    }
    if (datas.length > 1) {
        ElMessage.warning('只能选择一条数据进行修改操作！')
        return
    }
    details.id = datas[0].id
    details.open = true
}

const remove = async (datas: VMenuManagement[]) => {
    const ids: string[] = []
    if (!datas.length) {
        ElMessage.warning('请至少选择一条数据进行删除操作！')
        return
    }
    datas.forEach(item => {
        ids.push(item.id!)
    })
    const res = await removeMenu(ids) as unknown as HttpResponse
    if (res.ok) {
        ElMessage.success('删除成功!')
        table.value.query()
    } else {
        ElMessage.error('删除失败!')
    }
}

const data = reactive<TableCardType<VMenuManagement>>({
    name: '菜单管理',
    data: [],
    searchBox: {
        columns: [
            { id: 'name', name: '菜单名称', type: SearchBoxColumnType.Text, placeholder: '请输入菜单名称' },
            {
                id: 'role', name: '角色', type: SearchBoxColumnType.Selection, placeholder: '请选择角色', items: [
                    { text: '管理员', value: '1' },
                    { text: '用户', value: '2' }
                ]
            }
        ]
    },
    buttons: [
        { name: '新建', type: 'success', onclick: add, icon: Plus },
        { name: '修改', type: 'primary', onclick: edit, icon: Edit },
        { name: '删除', type: 'danger', onclick: remove, icon: Delete },
    ],
    columns: [
        { id: 'name', name: '菜单名称', type: SearchBoxColumnType.Text },
        { id: 'parentName', name: '上级菜单名称', type: SearchBoxColumnType.Text },
        { id: 'path', name: '路径', type: SearchBoxColumnType.Text },
        { id: 'icon', name: '图标', type: SearchBoxColumnType.Text },
        { id: 'visible', name: '启用状态', type: SearchBoxColumnType.Switch }
    ],
    query: listMenu
})
</script>

<style lang="less" scoped></style>